package com.daisuxia.web.controller;

import static com.daisuxia.web.pojo.BorrowOrder.borrowStatusMap_shenheFail;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.daisuxia.back.test.SerializeUtil;
import com.daisuxia.back.utils.SpringUtils;
import com.daisuxia.constant.Constant;
import com.daisuxia.web.listener.IndexInit;
import com.daisuxia.web.pojo.*;
import com.daisuxia.web.pojo.index.IndexDto;
import com.daisuxia.web.service.*;
import com.daisuxia.web.util.IndexUtil;
import com.daisuxia.web.util.JSONUtil;
import com.daisuxia.web.util.MapUtils;
import com.daisuxia.web.util.WriteUtil;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPool;

/**
 * 首页
 * @author gaoyuhai
 * 2016-12-10 上午11:29:15
 */
@Controller
public class IndexController extends BaseController {
	
	private static Logger loger = Logger.getLogger(IndexController.class);
	@Autowired
	private IIndexService indexService;
	@Autowired
	private IInfoIndexService infoIndexService;
	
	@Autowired
	@Qualifier("reportService")
	private IReportService reportService ;
	@Autowired
	JedisCluster jedisCluster;
	@Autowired
	private BorrowOrderService borrowOrderService;
	@Autowired
	private IBackConfigParamsService backConfigParamsService;
	/**
	 * 更新系统缓存<br>
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @param sysConfig
	 * @return
	 */
	@RequestMapping("updateCache_otherUpdateMe")
	public void updateCache_otherUpdateMe(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		boolean succ = false;
		try {
			new IndexInit().updateCache();
			//刷新首页缓存zjb
			initIndex();
				succ = true;
		} catch (Exception e) {
			loger.error("updateCache error ", e);
			succ = false;
		}
 		SpringUtils.renderDwzResult(response, succ, succ ? "刷新缓存成功" : "刷新缓存失败");
	}
	/**
	 * gotoindex
	 * @param request
	 * @param response
	 * @param model
	 */
	/*@RequestMapping(value="/credit-app/index")
	public void gotoIndex(HttpServletRequest request,HttpServletResponse response, Model model){
		loger.info(getIpAddr(request)+"  goto index...");
		String deviceId = request.getParameter("deviceId");//设备号
		String telephone=request.getParameter("mobilePhone");
		String appVersion = request.getParameter("appVersion");//app版本号
		loger.info("设备号："+deviceId);
		loger.info("手机号码："+telephone);
		if(StringUtils.isBlank(deviceId)){//设备号为空
			sendDefault(response);
			loger.info("设备号或者手机号不存在,默认展示");
		}else{
			User user = loginFrontUserByDeiceId(request);
			try{
				if(null == user){
					sendDefault(response);
					loger.info("用户ID不存在，设备号为："+deviceId+",手机号为：,"+telephone+"默认展示 ");
				}else{
					sendDynamic(response, user.getId());
				}
			}catch(Exception e){
				sendDefault(response);
			}
			
		}
	}*/
	@RequestMapping(value="getNewAppUpgrade")
	public String getNewAppUpgrade(){
		return "content/newAppUpgrade.jsp";
	}
	
	/**
	 * gotoindex
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping(value="/credit-app/index")
	public void gotoIndex(HttpServletRequest request,HttpServletResponse response, Model model){
		loger.info(getIpAddr(request)+"  goto index...");
		String deviceId = request.getParameter("deviceId");//设备号
		String telephone=request.getParameter("mobilePhone");
		String appVersion = request.getParameter("appVersion");//app版本号
		String newVersionUpgradeUrl = "";//APP新版本升级
		newVersionUpgradeUrl = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/"+"getNewAppUpgrade";
		loger.info("设备号："+deviceId);
		loger.info("手机号码："+telephone);
		if(StringUtils.isBlank(deviceId)){//设备号为空
			sendDefault(response);
			loger.info("设备号或者手机号不存在,默认展示");
		}else{
			User user = loginFrontUserByDeiceId(request);
			try{
				if(null == user){
					sendDefault2(response,appVersion,newVersionUpgradeUrl);
					loger.info("用户ID不存在，设备号为："+deviceId+",手机号为：,"+telephone+"默认展示 ");
				}else{
					sendDynamic2(response, user.getId(),appVersion,newVersionUpgradeUrl);
				}
			}catch(Exception e){
				sendDefault(response);
			}
			
		}
	}
	
	private void sendDynamic2(HttpServletResponse response, String userId,
			String appVersion,String newVersionUpgradeUrl) {
		loger.info("sendDynamic2:userid="+userId);
		String indexJson = null;
		try{
//			indexJson = jedisCluster.get(Constant.CACHE_INDEX_INFO_KEY+userId);//获取用户信息数据
			if(StringUtils.isBlank(indexJson)){
				HashMap<String,Object> map = new HashMap<String,Object>();
				map.put("USER_ID", userId);
				InfoIndexInfo indexInfo = this.indexService.searchInfoIndexInfo(map);
				
				User user = this.indexService.searchUserByIndex(map);
				
				if(null==indexInfo){
					loger.info("info_user_info表中无"+userId+"用户记录");
					sendDefault(response);
				}else{
					user = setMaxAmount(user);
					//infoIndexInfo 存在 开始组装
//					indexJson = jedisCluster.get(Constant.CACHE_INDEX_KEY);//获取默认数据-备用
					if(StringUtils.isBlank(indexJson)){//未获取到
						indexJson = initIndex();
						if(StringUtils.isBlank(indexJson)){
							loger.info("静态展示-2-1-");
							indexJson = JSONUtil.beanToJson(this.indexService.getDefaultJson());//发送静态字符串
						}
					}
					String indexJsonRe = getJsonStr2(indexJson, indexInfo,user,appVersion,newVersionUpgradeUrl);
					if(StringUtils.isBlank(indexJsonRe)){
						WriteUtil.writeDataToApp(response, indexJson);
					}else{
						indexJson=indexJsonRe;
					}
					jedisCluster.set(Constant.CACHE_INDEX_INFO_KEY+userId,indexJson);
					loger.info("动态返回");
					WriteUtil.writeDataToApp(response, indexJson);
				}
			}else{
				loger.info("用户"+userId+"存在于缓存");
				WriteUtil.writeDataToApp(response, indexJson);
			}
		}catch(Exception e){
			sendDefault(response);
			loger.info("gotoIndex-exception :"+e.getMessage());
		}
		
	}
	
	
	/**
	 * 返回默认数据
	 */
	private void sendDefault2(HttpServletResponse response,String appVersion,String newVersionUpgradeUrl){
 		String indexJson = null;
		try{
			indexJson = jedisCluster.get(Constant.CACHE_INDEX_KEY);//获取默认数据--{"message":"访问首页成功","data":{"user_loan_log_list":["尾号2269，正常还款，成功提额至1050元","尾号6547，成功借款1000元，申请至放款耗时3分钟","尾号2265，成功借款1000元，申请至放款耗时4分钟","尾号3313，正常还款，成功提额至1050元","尾号3369，成功借款1000元，申请至放款耗时3分钟","尾号1225，正常还款，成功提额至1050元","尾号6681，成功借款1000元，申请至放款耗时3分钟","尾号5423，成功借款1000元，申请至放款耗时4分钟","尾号3212，正常还款，成功提额至1050元","尾号7634，成功借款1000元，申请至放款耗时5分钟"],"index_images":[{"title":"你借我还活动","sort":"1","reurl":"http://192.168.1.161:8080/ygmmr/index","url":"http://super.xianjinxia.com/common/web/images/index_banner0000.png?typeImg=1"},{"title":"首页活动一","sort":"2","reurl":"http://192.168.1.161:8080/jsaward/awardCenter/drawAwardIndex","url":"http://super.xianjinxia.com/common/web/images/index_banner111.png"},{"title":"首页活动二","sort":"3","reurl":"http://192.168.1.161:8080/gotoDrawAwardsIndex","url":"http://super.xianjinxia.com/common/web/images/index_banner2.png"},{"title":"首页活动三","sort":"4","reurl":"http://192.168.1.161:8080/gotoAboutIndex","url":"http://super.xianjinxia.com/common/web/images/index_banner3.png"}],"amount_days_list":{"amounts":["20000","30000","40000","50000","60000","70000","80000","90000","100000","110000","120000","130000","140000","150000","160000","170000","180000","190000","200000","210000","220000","230000","240000","250000","260000","270000","280000","290000","300000","310000","320000","330000","340000","350000","360000","370000","380000","390000","400000","410000","420000","430000","440000","450000","460000","470000","480000","490000","500000","510000","520000","530000","540000","550000","560000","570000","580000","590000","600000","610000","620000","630000","640000","650000","660000","670000","680000","690000","700000","710000","720000","730000","740000","750000","760000","770000","780000","790000","800000","810000","820000","830000","840000","850000","860000","870000","880000","890000","900000","910000","920000","930000","940000","950000","960000","970000","980000","990000","1000000"],"days":["7","14"],"interests":["49000","75000"]},"item":{"verify_loan_pass":0,"card_title":"贷速侠","card_amount":"1000000","card_verify_step":"认证0/5","verify_loan_nums":"0"},"today_last_amount":"123400"},"code":"0"}
			if(StringUtils.isBlank(indexJson)){//未获取到
				indexJson = initIndex();
				if(StringUtils.isBlank(indexJson)){
					loger.info("静态展示-0-");
					indexJson = JSONUtil.beanToJson(this.indexService.getDefaultJson());//发送静态字符串
				}
			}
			//TODO
			JSONObject jsonObj = JSONObject.fromObject(indexJson);
			String code = jsonObj.getString("code");
			if(code.equals("0")){
				JSONObject data =  JSONObject.fromObject(jsonObj.get("data"));
				JSONObject item =  JSONObject.fromObject(data.get("item"));
				//item
				//提醒是否升级
//				if ("2.1.0".equals(appVersion)) {
//					item.put("whether_need_upgrade", 1);
//				}else{
//					item.put("whether_need_upgrade", 0);
//				}
				//app升级url
				item.put("new_version_upgrade_url",newVersionUpgradeUrl);
				data.put("item", item);
				jsonObj.put("data", data);
				indexJson=jsonObj.toString();
			}else if(code.equals("-1")){
				WriteUtil.writeDataToApp(response, indexJson);
			}
			
			loger.info("DEFAULT-SEND");
			WriteUtil.writeDataToApp(response, indexJson);
		}catch(Exception e){
			loger.info("gotoIndex-exception :"+e.getMessage());
			loger.info("静态展示-1-");
			WriteUtil.writeDataToApp(response, this.indexService.getDefaultJson());
		}
	}
	
	
	/**
	 * 返回默认数据
	 */
	private void sendDefault(HttpServletResponse response){
 		String indexJson = null;
		try{
			indexJson = jedisCluster.get(Constant.CACHE_INDEX_KEY);//获取默认数据--{"message":"访问首页成功","data":{"user_loan_log_list":["尾号2269，正常还款，成功提额至1050元","尾号6547，成功借款1000元，申请至放款耗时3分钟","尾号2265，成功借款1000元，申请至放款耗时4分钟","尾号3313，正常还款，成功提额至1050元","尾号3369，成功借款1000元，申请至放款耗时3分钟","尾号1225，正常还款，成功提额至1050元","尾号6681，成功借款1000元，申请至放款耗时3分钟","尾号5423，成功借款1000元，申请至放款耗时4分钟","尾号3212，正常还款，成功提额至1050元","尾号7634，成功借款1000元，申请至放款耗时5分钟"],"index_images":[{"title":"你借我还活动","sort":"1","reurl":"http://192.168.1.161:8080/ygmmr/index","url":"http://super.xianjinxia.com/common/web/images/index_banner0000.png?typeImg=1"},{"title":"首页活动一","sort":"2","reurl":"http://192.168.1.161:8080/jsaward/awardCenter/drawAwardIndex","url":"http://super.xianjinxia.com/common/web/images/index_banner111.png"},{"title":"首页活动二","sort":"3","reurl":"http://192.168.1.161:8080/gotoDrawAwardsIndex","url":"http://super.xianjinxia.com/common/web/images/index_banner2.png"},{"title":"首页活动三","sort":"4","reurl":"http://192.168.1.161:8080/gotoAboutIndex","url":"http://super.xianjinxia.com/common/web/images/index_banner3.png"}],"amount_days_list":{"amounts":["20000","30000","40000","50000","60000","70000","80000","90000","100000","110000","120000","130000","140000","150000","160000","170000","180000","190000","200000","210000","220000","230000","240000","250000","260000","270000","280000","290000","300000","310000","320000","330000","340000","350000","360000","370000","380000","390000","400000","410000","420000","430000","440000","450000","460000","470000","480000","490000","500000","510000","520000","530000","540000","550000","560000","570000","580000","590000","600000","610000","620000","630000","640000","650000","660000","670000","680000","690000","700000","710000","720000","730000","740000","750000","760000","770000","780000","790000","800000","810000","820000","830000","840000","850000","860000","870000","880000","890000","900000","910000","920000","930000","940000","950000","960000","970000","980000","990000","1000000"],"days":["7","14"],"interests":["49000","75000"]},"item":{"verify_loan_pass":0,"card_title":"贷速侠","card_amount":"1000000","card_verify_step":"认证0/5","verify_loan_nums":"0"},"today_last_amount":"123400"},"code":"0"}
			if(StringUtils.isBlank(indexJson)){//未获取到
				indexJson = initIndex();
				if(StringUtils.isBlank(indexJson)){
					loger.info("静态展示-0-");
					indexJson = JSONUtil.beanToJson(this.indexService.getDefaultJson());//发送静态字符串
				}
			}
			loger.info("DEFAULT-SEND");
			WriteUtil.writeDataToApp(response, indexJson);
		}catch(Exception e){
			loger.info("gotoIndex-exception :"+e.getMessage());
			loger.info("静态展示-1-");
			WriteUtil.writeDataToApp(response, this.indexService.getDefaultJson());
		}
	}
	
	/**
	 * 返回动态数据
	 * @param response
	 */
	private void sendDynamic(HttpServletResponse response, String userId){
		loger.info("sendDynamic:userid="+userId);
		String indexJson = null;
		try{
			//indexJson = jedisCluster.get(Constant.CACHE_INDEX_INFO_KEY+userId);//获取用户信息数据
			if(StringUtils.isBlank(indexJson)){
				HashMap<String,Object> map = new HashMap<String,Object>();
				map.put("USER_ID", userId);
				InfoIndexInfo indexInfo = this.indexService.searchInfoIndexInfo(map);
				
				User user = this.indexService.searchUserByIndex(map);
				
				if(null==indexInfo){
					loger.info("info_user_info表中无"+userId+"用户记录");
					sendDefault(response);
				}else{
					user = setMaxAmount(user);
					//infoIndexInfo 存在 开始组装
					indexJson = jedisCluster.get(Constant.CACHE_INDEX_KEY);//获取默认数据-备用
					if(StringUtils.isBlank(indexJson)){//未获取到
						indexJson = initIndex();
						if(StringUtils.isBlank(indexJson)){
							loger.info("静态展示-2-1-");
							indexJson = JSONUtil.beanToJson(this.indexService.getDefaultJson());//发送静态字符串
						}
					}
					String indexJsonRe = getJsonStr(indexJson, indexInfo,user);
					if(StringUtils.isBlank(indexJsonRe)){
						WriteUtil.writeDataToApp(response, indexJson);
					}else{
						indexJson=indexJsonRe;
					}
//					jedisCluster.set(Constant.CACHE_INDEX_INFO_KEY+userId,indexJson);
					loger.info("动态返回");
					WriteUtil.writeDataToApp(response, indexJson);
				}
			}else{
				loger.info("用户"+userId+"存在于缓存");
				WriteUtil.writeDataToApp(response, indexJson);
			}
		}catch(Exception e){
			sendDefault(response);
			loger.info("gotoIndex-exception :"+e.getMessage());
		}
	}
	
	/**
	 * 
	 * @param indexJson
	 * @param indexInfo
	 * @param user
	 * @return
	 */
	private String getJsonStr(String indexJson,InfoIndexInfo indexInfo,User user){
		try{
 			JSONObject jsonObj = JSONObject.fromObject(indexJson);
			String code = jsonObj.getString("code");
			if(code.equals("0")){
				JSONObject data =  JSONObject.fromObject(jsonObj.get("data"));
				JSONObject amount_days_list =  JSONObject.fromObject(data.get("amount_days_list"));
				JSONObject item =  JSONObject.fromObject(data.get("item"));
				Object amounts = null;
				Object interests = null;
				Object cardAmount = null;
				if(null != user){
					amounts = IndexUtil.getAmounts(Integer.parseInt(user.getAmountMin()),Integer.parseInt(user.getAmountMax()));
					interests = IndexUtil.getInterests(indexInfo,user);
					cardAmount = user.getAmountMax();

				}else{
					amounts = IndexUtil.getAmounts(Integer.parseInt(indexInfo.getAmountMin()),Integer.parseInt(indexInfo.getCardAmount()));
					interests = IndexUtil.getInterests(indexInfo);
					cardAmount = indexInfo.getCardAmount();
				}
				//amounts
				amount_days_list.put("amounts", amounts);
				//interests
				amount_days_list.put("interests", interests);
				//item
				item.put("card_amount", cardAmount);
				item.put("card_verify_step", Constant.CARD_VERIFY_STEP+indexInfo.getAuthSum()+"/"+indexInfo.getAuthCount());
				item.put("verify_loan_nums", indexInfo.getAuthSum());
				item.put("verify_loan_pass", IndexUtil.getVerifyLoanPass(indexInfo.getAuthSum()+"", indexInfo.getAuthCount()+""));
				if(indexInfo.getBorrowStatus().equals(Constant.STATUS_VALID)){//存在借款
					if(!checkBankNo(indexInfo)){
						HashMap<String,Object> map = new HashMap<String,Object>();
						map.put("userId", indexInfo.getUserId());
						this.infoIndexService.authBank(map);//设置银行卡号
						
						map = new HashMap<String,Object>();
						map.put("USER_ID", indexInfo.getUserId());
						indexInfo = this.indexService.searchInfoIndexInfo(map);//重新查询
						loger.error("indexInfo-getBankNo:"+indexInfo.getBankNo());
					}
					item.put("loan_infos", this.indexService.getLoanInfos(indexInfo));
				}
				if(null != user){
					Map<String,String> interval = borrowOrderService.findAuditFailureOrderByUserId(user.getId());
					item.put("next_loan_day", interval.get("nextLoanDay"));
				}
				else{
					item.put("next_loan_day", 0);
				}


				data.put("amount_days_list", amount_days_list);
				data.put("item", item);
				
				jsonObj.put("data", data);
				return jsonObj.toString();
			}else if(code.equals("-1")){
				return indexJson;
			}
		}catch(Exception e){
			e.printStackTrace();
			loger.info("静态展示-3-");
			return this.indexService.getDefaultJson();
		}
		loger.info("静态展示-4-");
		return this.indexService.getDefaultJson();
	}
	
	/**
	 * 兼容app版本为2.2.0
	 * @param indexJson
	 * @param indexInfo
	 * @param user
	 * @param appVersion
	 * @return
	 */
	private String getJsonStr2(String indexJson,InfoIndexInfo indexInfo,User user,String appVersion,String newVersionUpgradeUrl){
		try{
 			JSONObject jsonObj = JSONObject.fromObject(indexJson);
			String code = jsonObj.getString("code");
			if(code.equals("0")){
				JSONObject data =  JSONObject.fromObject(jsonObj.get("data"));
				JSONObject amount_days_list =  JSONObject.fromObject(data.get("amount_days_list"));
				JSONObject item =  JSONObject.fromObject(data.get("item"));
				JSONArray days=amount_days_list.getJSONArray("days");
				Object amounts = null;
				Object interests = null;
				Object cardAmount = null;
				Object creditVet = null;
				Object accountManage = null;
				Object accrual = null;
				if(null != user){
					amounts = IndexUtil.getAmounts(Integer.parseInt(user.getAmountMin()),Integer.parseInt(user.getAmountMax()));
					interests = IndexUtil.getInterests(indexInfo,user);
					creditVet = IndexUtil.getCreditVet(indexInfo, user,days);
					accountManage = IndexUtil.getAccountManage(indexInfo, user,days);
					accrual = IndexUtil.getAccrual(indexInfo, user,days);
					cardAmount = user.getAmountMax();

				}else{
					amounts = IndexUtil.getAmounts(Integer.parseInt(indexInfo.getAmountMin()),Integer.parseInt(indexInfo.getCardAmount()));
					interests = IndexUtil.getInterests(indexInfo);
					creditVet = IndexUtil.getCreditVet(indexInfo, user,days);
					accountManage = IndexUtil.getAccountManage(indexInfo, user,days);
					accrual = IndexUtil.getAccrual(indexInfo, user,days);
					cardAmount = indexInfo.getCardAmount();
				}
				//amounts
				amount_days_list.put("amounts", amounts);
				//interests
//TODO  给你用已启用 2.2.0 版本页面	
				
				//信审查询费
				amount_days_list.put("creditVet",creditVet);
				//账户管理费
				amount_days_list.put("accountManage",accountManage);
				//利息
				amount_days_list.put("accrual",accrual);
				
			/*	if ("2.2.0".equals(appVersion)) {
					//信审查询费
					amount_days_list.put("creditVet",creditVet);
					//账户管理费
					amount_days_list.put("accountManage",accountManage);
					//利息
					amount_days_list.put("accrual",accrual);
				}else {
					amount_days_list.put("interests", interests);
				}*/
				
				
				
				
				//item
				item.put("card_amount", cardAmount);
//TODO  给你用已启用 2.2.0 版本页面
				item.put("card_verify_step",Constant.CARD_VERIFY_STEP+(indexInfo.getAuthInfo()+indexInfo.getAuthContacts()+indexInfo.getAuthMobile()+indexInfo.getAuthSesame())+"/"+4);
				
				/*if ("2.2.0".equals(appVersion)) {
					item.put("card_verify_step",Constant.CARD_VERIFY_STEP+(indexInfo.getAuthInfo()+indexInfo.getAuthContacts()+indexInfo.getAuthMobile()+indexInfo.getAuthSesame())+"/"+4);
				}else{
					item.put("card_verify_step", Constant.CARD_VERIFY_STEP+indexInfo.getAuthSum()+"/"+indexInfo.getAuthCount());
				}*/
				item.put("verify_loan_nums", indexInfo.getAuthSum());
//TODO  给你用已启用 2.2.0 版本页面		
				item.put("verify_loan_pass", IndexUtil.getVerifyLoanPass2(indexInfo.getAuthSum()+"", indexInfo.getAuthCount()+"",indexInfo.getAuthBank()+""));
				
			/*	if ("2.2.0".equals(appVersion) && indexInfo.getAuthSum()==4 && indexInfo.getAuthBank()==0) {//2.2.0版本的银行卡逻辑(完成必填项的4项，且未完成项是银行卡)
					item.put("verify_loan_pass", IndexUtil.getVerifyLoanPass2(indexInfo.getAuthSum()+"", indexInfo.getAuthCount()+"",indexInfo.getAuthBank()+""));
				}else{
					item.put("verify_loan_pass", IndexUtil.getVerifyLoanPass(indexInfo.getAuthSum()+"", indexInfo.getAuthCount()+""));
				}*/
				//总认证数
				item.put("all_auth_Count", indexInfo.getAuthCount());
				//提醒是否升级
//				if ("2.1.0".equals(appVersion)) {
//					item.put("whether_need_upgrade", 1);
//				}else{
//					item.put("whether_need_upgrade", 0);
//				}
				//app升级url
				item.put("new_version_upgrade_url",newVersionUpgradeUrl);
				if(indexInfo.getBorrowStatus().equals(Constant.STATUS_VALID)){//存在借款
					if(!checkBankNo(indexInfo)){
						HashMap<String,Object> map = new HashMap<String,Object>();
						map.put("userId", indexInfo.getUserId());
						this.infoIndexService.authBank(map);//设置银行卡号
						
						map = new HashMap<String,Object>();
						map.put("USER_ID", indexInfo.getUserId());
						indexInfo = this.indexService.searchInfoIndexInfo(map);//重新查询
						loger.error("indexInfo-getBankNo:"+indexInfo.getBankNo());
					}
					item.put("loan_infos", this.indexService.getLoanInfos(indexInfo));
				}
				if(null != user){
					Map<String,String> interval = borrowOrderService.findAuditFailureOrderByUserId(user.getId());
					item.put("next_loan_day", interval.get("nextLoanDay"));
				}
				else{
					item.put("next_loan_day", 0);
				}


				data.put("amount_days_list", amount_days_list);
				//获取用户最近借款状态 代替风控
				// 如果最近借款被拒绝, 那么就显示问号, 跳转去其他的app
				// 0 不显示 1显示
				item.put("risk_status","0");
				BorrowOrder bo = borrowOrderService.selectBorrowOrderNowUseId(Integer.valueOf(user.getId()));
				if(bo!=null){
					//借款审核被拒绝 添加全局控制开关 1 打开 0 关闭
					HashMap<String,Object> params = new HashMap<String,Object>();
					params.put("sysType","SYS_NOCACHE");
					params.put("syskey","SYJ_SWITCH");
					//params.put("sysName","");
					List<BackConfigParams> list = backConfigParamsService.findParams(params);
					String offon = "1";
					if(list.size()==1){
						offon = list.get(0).getSysValue();
					}

					if(borrowStatusMap_shenheFail.containsKey(bo.getStatus())
							&&"1".equals(offon)){
						item.put("risk_status","1");
					}
				}


				data.put("item", item);
				
				jsonObj.put("data", data);
				return jsonObj.toString();
			}else if(code.equals("-1")){
				return indexJson;
			}
		}catch(Exception e){
			e.printStackTrace();
			loger.info("静态展示-3-");
			return this.indexService.getDefaultJson();
		}
		loger.info("静态展示-4-");
		return this.indexService.getDefaultJson();
	}
	/**
	 * 设置第二版amounts为0的问题
	 * @param user
	 * @return
	 */
	private User setMaxAmount(User user){
		String min = "1";
		String max = "1";
		if(StringUtils.isNotBlank(user.getAmountMin())){
			if("0".equals(user.getAmountMin())){
				 min = "1";
			}else{
				min = user.getAmountMin();
			}
		}else{
			min = "1";
		}
		user.setAmountMin(min);
		
		if(StringUtils.isNotBlank(user.getAmountMax())){
			if("0".equals(user.getAmountMax())){
				max = "1";
			}else{
				max = user.getAmountMax();
			}
		}else{
			max = "1";
		}
		user.setAmountMax(max);
		return user;
	}
	/**
	 * 初始化index
	 * 
	 */
	private String initIndex() {
		loger.info("indexController-initIndex start...");
		HashMap<String,Object> dtoMap = new HashMap<String,Object>();
		IndexDto iDto = this.indexService.searchIndexDto(dtoMap);
		if(null!=iDto && StringUtils.isNotBlank(iDto.getContent())){
			return iDto.getContent();
		}
		
		HashMap<String,Object> resultMap = MapUtils.getResultMap("0","访问首页成功");
		HashMap<String,Object> dataMap = new HashMap<String,Object>();//存放数据
		
		HashMap<String,Object> map = new HashMap<String,Object>();
		map.put("NOT_SELECT", Constant.STATUS_VALID);
		InfoIndex index = this.indexService.searchInfoIndex(map);//查询首页内容
		
		List<InfoNotice> noticeList = null;
		
		if(null!=index){
			HashMap<String,Object> itemMap = new HashMap<String,Object>();
			itemMap.put("card_title", index.getCard_title());
			itemMap.put("card_amount", index.getCard_amount());
			itemMap.put("card_verify_step", Constant.CARD_VERIFY_STEP+index.getAuth_min()+"/"+index.getAuth_max());
			itemMap.put("verify_loan_pass", IndexUtil.getVerifyLoanPass(index.getAuth_min(), index.getAuth_max()));
			itemMap.put("verify_loan_nums", index.getAuth_min());
			dataMap.put("item", itemMap);
			
			HashMap<String,Object> amountDaysListMap = new HashMap<String,Object>();
			
			amountDaysListMap.put("days", IndexUtil.getDays(index));//借款日期
			
			amountDaysListMap.put("interests", IndexUtil.getInterests(index));//到账金额
			
			amountDaysListMap.put("amounts", IndexUtil.getAmounts(index));//金额列表
		
			//贷速侠 可能会用到
//			amountDaysListMap.put("creditVet", IndexUtil.getAmounts(index));//金额列表
//			amountDaysListMap.put("accountManage", IndexUtil.getAccountManageDays(index));//金额列表
//			amountDaysListMap.put("accrual", IndexUtil.getAccrualDays(index));//利息
			
			
			dataMap.put("amount_days_list", amountDaysListMap);
			
			Integer noticeSize = null;
			List<InfoImage> imageList = null;
			try{
				noticeSize = Integer.parseInt(index.getNotice_size());
			}catch(Exception e){
				
			}
			if(noticeSize==null ){
				noticeSize = Constant.INDEX_LIMIT;
			}
			
			map.put("COUNT_XJX", noticeSize);
			noticeList = this.indexService.searchInfoNoticeByIndex(map);//查询公告
			dataMap.put("user_loan_log_list", IndexUtil.getUserLoanLogList(noticeList));
			
			map.put("STATUS", Constant.STATUS_VALID);
			imageList = indexService.searchInfoImage(map);//查询图片
			dataMap.put("index_images", IndexUtil.getInfoImageList(imageList));
			
			dataMap.put("today_last_amount", index.getToday_last_amount());
			
			resultMap.put("data", dataMap);
			
			//loger.info("resultMap="+resultMap);
			String indexJson = "";
			try {
				indexJson = JSONUtil.beanToJson(resultMap);
				IndexDto indexDto = new IndexDto(indexJson,Constant.STATUS_VALID);
				this.indexService.saveIndexDto(indexDto);
				jedisCluster.set(Constant.CACHE_INDEX_KEY, indexJson);
				return indexJson;
			} catch (Exception e) {
				e.printStackTrace();
			}
			//loger.info("JSONUtil.beanToJson(resultMap):"+indexJson);
		}else{
			loger.error("-----------------INDEX-ERROR-ISNULL-----------------");
		}
		return null;
	}
	/**
	 * 设置审核拒绝时button事件
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping(value="/credit-loan/confirm-failed-loan")
	public void setBorrowStatus(HttpServletRequest request,HttpServletResponse response, Model model){
		loger.info("setBorrowStatus start...");
		String deviceId = request.getParameter("deviceId");//设备号
		String telephone=request.getParameter("mobilePhone");
		loger.info("设备号："+deviceId);
		if(StringUtils.isBlank(deviceId)){//设备号为空
			HashMap<String,Object> reMap = MapUtils.getResultMapByError("-1", "请您检查网络再试");
			WriteUtil.writeDataToApp(response, JSONUtil.beanToJson(reMap));
		}else{
			User user = null;
			try{
				byte[] userInfo = jedisCluster.get((LOGING_DEVICE_PREFIX+deviceId+telephone).getBytes());
				user = (User)SerializeUtil.unserialize(userInfo);
			}catch(Exception e){
				
			}
			try{
				if(null!=user){
					HashMap<String, Object> map = new HashMap<String, Object>();
					map.put("USER_ID", user.getId());
					map.put("BORROW_STATUS", "0");
					this.indexService.updateInfoUserInfoBorrowStatus(map );
					HashMap<String,Object> reMap = MapUtils.getResultMap("0", "初始化成功");
					this.infoIndexService.sendDynamic(Integer.parseInt(user.getId()));//初始化用户动态信息
					WriteUtil.writeDataToApp(response, JSONUtil.beanToJson(reMap));
				}else{
					HashMap<String,Object> reMap = MapUtils.getResultMapByError("-1", "请您检查网络再试");
					WriteUtil.writeDataToApp(response, JSONUtil.beanToJson(reMap));
				}
			}catch(Exception e){
				HashMap<String,Object> reMap = MapUtils.getResultMapByError("-1", "请您检查网络再试");
				WriteUtil.writeDataToApp(response, JSONUtil.beanToJson(reMap));
			}
		}
	}
	/**
	 * 上报
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping(value="/credit-app/device-report")
	public void deviceReport(HttpServletRequest request,HttpServletResponse response, Model model){
		loger.info("IndexController deviceReport start");
		String identifierId = request.getParameter("IdentifierId");
		String appMarket = request.getParameter("appMarket");
		String device_id = request.getParameter("device_id");
		String installed_time = request.getParameter("installed_time");
		String net_type = request.getParameter("net_type");
		String uid = request.getParameter("uid");
		String username = request.getParameter("username");
		loger.info("parameter IdentifierId:"+identifierId +",appMarket:"+appMarket+",device_id:"+device_id+",installed_time:"+installed_time+",net_type:"+net_type+",uid:"+uid+",username:"+username);
		
		InfoReport infoReport = new InfoReport();
		infoReport.setIdentifierId(identifierId);
		infoReport.setAppMarket(appMarket);
		infoReport.setDeviceId(device_id);
		infoReport.setInstalledTime(installed_time);
		infoReport.setNetType(net_type);
		infoReport.setUid(uid);
		infoReport.setUserName(username);
		
		reportService.saveReport(infoReport);
		
		JSONObject json=new JSONObject();
		json.put("code","0");
		JSONUtil.toObjectJson(response, json.toString());
		
		loger.info("IndexController deviceReport end");
	}
	@RequestMapping(value="/credit-app/index0")
	public void Test0(HttpServletRequest request,HttpServletResponse response, Model model){
//		System.out.println("user="+jedisCluster.get("INDEX_INFO_33"));
		
//		System.out.println("---------------------------------------------");
		
		
		 Map<String, JedisPool> clusterNodes = jedisCluster.getClusterNodes();
		 for(String k : clusterNodes.keySet()){  
	            JedisPool jp = clusterNodes.get(k);  
	            Jedis jedis = jp.getResource(); 
	            Set<String> keys = jedis.keys("*");
				Iterator<String> it = keys.iterator();
				StringBuffer sb = new StringBuffer();
				while (it.hasNext()) {
					String key = it.next();
//					System.out.println("key=" + key);
				}
	        }  
	}
	/**
	 * 是否老用户
	 * @param request
	 * @param response
	 * @param model
	 */
	private static String oldUserUrl = "http://super.daisuxia.com/common/web/images/olduser.png";
	@RequestMapping(value="/credit-app/old_user")
	public void creditOldUser(HttpServletRequest request,HttpServletResponse response, Model model){
		loger.info("creditOldUser start");
		sendDefaultOldTwo(response);
//		String deviceId = request.getParameter("deviceId");//设备号
//		loger.info("是否老用户-设备号："+deviceId);
//		if(StringUtils.isBlank(deviceId)){//设备号为空
//			sendOldUser(response);//显示
//			loger.info("设备号不存在,默认弹出");
//		}else{
//			User user = null;
//			try{
//				user = loginFrontUserByDeiceId(request);
//			}catch(Exception e){
//				sendOldUser(response);//显示
//			}
//			try{
//				if(null!=user){//注册登录后
//					String phone = user.getUserPhone();
//					if(StringUtils.isNotBlank(phone)){
//						loger.info("phone="+phone);
//						HashMap<String, Object> map=new HashMap<String, Object>();
//						map.put("TELEPHONE", phone);
//						map.put("DISPLAY", Constant.STATUS_VALID);//显示
//						//查询old
//						UserInfoOld oldUser = this.infoIndexService.searchUserInfoOld(map);
//						if(null!=oldUser){//需要显示
//							loger.info("olduser-telephone:"+oldUser.getTelephone()+" olduser-display:"+oldUser.getDisplay());
//							sendOldUser(response);//显示
//							map=new HashMap<String, Object>();
//							map.put("TELEPHONE", phone);
//							map.put("DISPLAY", Constant.STATUS_UN_VALID);//不显示
//							this.infoIndexService.updateUserInfoOld(map);
//						}else{
//							loger.info("新用户"+phone+"不显示");
//							sendDefaultOld(response);//不显示
//						}
//					}else{
//						sendOldUser(response);//显示
//					}
//				}else{//没有注册登录
//					sendOldUser(response);//显示
//				}
//			}catch(Exception e){
//				e.printStackTrace();
//				sendOldUser(response);//显示
//			}
//			
//		}
		loger.info("creditOldUser end");
	}
	/**
	 * 不显示--第二版
	 * @param response
	 */
	private void sendDefaultOldTwo(HttpServletResponse response){
		HashMap<String,Object> resultMap = MapUtils.getResultMap("0","访问老用户列表成功");
		HashMap<String,Object> dataMap = new HashMap<String,Object>();//存放数据
		dataMap.put("display", Constant.STATUS_UN_VALID);//不显示
		dataMap.put("imgurl", "");//不显示
		resultMap.put("data", dataMap);
		String json = JSONUtil.beanToJson(resultMap);
		JSONUtil.toObjectJson(response, json.toString());
	}
	/**
	 * 不显示
	 * @param response
	 */
	private void sendDefaultOld(HttpServletResponse response){
		HashMap<String,Object> resultMap = MapUtils.getResultMap("0","访问老用户列表成功");
		HashMap<String,Object> dataMap = new HashMap<String,Object>();//存放数据
		dataMap.put("display", Constant.STATUS_UN_VALID);//不显示
		dataMap.put("imgurl", oldUserUrl);//不显示
		resultMap.put("data", dataMap);
		String json = JSONUtil.beanToJson(resultMap);
		JSONUtil.toObjectJson(response, json.toString());
	}
	/**
	 * 显示
	 * @param response
	 */
	private void sendOldUser(HttpServletResponse response){
		HashMap<String,Object> resultMap = MapUtils.getResultMap("0","访问老用户列表成功");
		HashMap<String,Object> dataMap = new HashMap<String,Object>();//存放数据
		dataMap.put("display", Constant.STATUS_VALID);//显示
		dataMap.put("imgurl", oldUserUrl);//显示
		resultMap.put("data", dataMap);
		String json = JSONUtil.beanToJson(resultMap);
		JSONUtil.toObjectJson(response, json.toString());
	}
	
	/**
	 * 校验银行卡
	 * @return
	 */
	private boolean checkBankNo(InfoIndexInfo indexInfo){
		if(null!=indexInfo){
			if(null!=indexInfo.getAuthBank()){
				if(Constant.STATUS_INT_VALID == indexInfo.getAuthBank()){//银行认证完成
					if(StringUtils.isNotBlank(indexInfo.getBankNo())){//银行卡号是否存在 
						return true;
					}
				}
			}
		}
		return false;
	}
	/**
	 * 关于我们
	 */
	@RequestMapping("gotoAboutIndex")
	public String gotoAboutIndex(HttpServletRequest request,HttpServletResponse response, Model model){
		String url = getAppConfig(request.getParameter("appName"), "ABOUT_ME_URL");
		/*return "content/aboutIndex";*/
		return url;
	}
/**
 * 进入静态活动页面
 * @param request
 * @param response
 * @param model
 * @return
 */
	@RequestMapping("gotoStaticIndex")
	public String gotoStaticIndex(HttpServletRequest request,HttpServletResponse response, Model model){
		String pageName=request.getParameter("pageName");
		return "content/"+pageName;
	}
	
	/**
	 * 进入拒就送
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
		@RequestMapping("gotoJujiuSong")
		public String gotoJujiuSong(HttpServletRequest request,HttpServletResponse response, Model model){
			return "content/jujiupeiIndex";
		}
	/**
	 * 还款方式
	 */
	@RequestMapping("gotoRepaymentType")
	public String gotoRepaymentType(HttpServletRequest request,HttpServletResponse response, Model model){
		model.addAttribute("type",request.getParameter("type"));
		return "repayment/repaymentTypeIndex";
	}
	
	/**
	 * 极速放款
	 */
	@RequestMapping("gotoDrawAwardsIndex")
	public String gotoDrawAwardsIndex(HttpServletRequest request,HttpServletResponse response, Model model){
		return "reward/drawAwardsIndex";
	}
}
